package com.boarsoft.boar.demo.order.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.demo.order.biz.PocOrderBiz;
import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.product.service.PocProductService;
import com.boarsoft.boar.demo.user.entity.PocAccount;
import com.boarsoft.boar.demo.user.service.PocAccountService;
import com.boarsoft.cache.Cache;
import com.boarsoft.cache.aop.Cached;
import com.boarsoft.common.Util;
import com.boarsoft.dao.sharding.bean.DaoSharding;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.core.Messenger;

@Component("orderServ")
public class PocOrderServiceImpl implements PocOrderService {

	private static final Logger log = LoggerFactory.getLogger(PocOrderServiceImpl.class);

	@Autowired
	@Lazy
	private PocAccountService acctSvc;

	@Autowired
	@Lazy
	private PocProductService prodSvc;

	@Autowired
	@Lazy
	private Cache redisCache;

	@Autowired
	private PocOrderBiz orderBiz;

	@Override
	@Cached(group = "order", index = 1)
	public PocOrder find(int tenantId, int orderId) {
		return orderBiz.findById(tenantId, orderId);
	}

	@Override
	@DaoSharding(policy = "tenant", index = 0)
	public boolean place(PocOrder order) {
		try {
			return orderBiz.placeOrder(order);
		} catch (Exception e) {
			log.error("Error on place order {}", order, e);
		}
		return false;
	}

	@Override
	public boolean finish(PocOrder order, boolean callType) {

		// 查询订单信息
		order = orderBiz.findById(order.getTenantId(), order.getOrderId());
		if (order != null) {
			log.debug("订单：" + order);
			if (order.getStatus() != PocOrder.STATUS_PLACE) {
				log.error("下单状态不正确...");
				return false;
			}
		} else {
			log.error("未找到订单");
			return false;
		}

		// 2.检查账户余额，账户余额下单时已扣减，仅减少冻结金额
		PocAccount userAccount = acctSvc.find(order.getTenantId(), order.getUserId());
		if (userAccount != null) {
			// System.out.println("账户：" + userAccount);
			if (userAccount.getLockAmount() >= order.getAmount()) {
				userAccount.setLockAmount(userAccount.getLockAmount() - order.getAmount());
			} else {
				log.error("冻结余额小于返还的冻结金额...");
				return false;
			}
		} else {
			log.error("未找到账户...");
			return false;
		}

		try {
			orderBiz.payOrder(order.getTenantId(), order, userAccount, callType);
			// 支付成功，发消息扣减库存
			Message m = new Message();
			m.setTarget("productTransaction");
			m.addRecipient("productTransactionSvc");
			m.setContent(order);
			try {
				Messenger.send(m);
			} catch (Exception e) {
				log.error("库存扣减消息发送失败，{}", order.getOrderId(), e);
			}
		} catch (Exception e) {
			log.error("支付失败...order info :" + order.toString());
			e.printStackTrace();
			// 给demo-product-app发送增加库存的冲正报文
			PocOrder newOrder = new PocOrder();
			newOrder.setAmount(order.getAmount());
			newOrder.setCreateTime(Util.getStdmfDateTime());
			newOrder.setModifyTime(Util.getStdmfDateTime());
			newOrder.setOrderId(order.getOrderId());
			newOrder.setProductId(order.getProductId());
			newOrder.setProductNum(order.getProductNum());
			newOrder.setStatus(PocOrder.STATUS_CANCEL);
			newOrder.setTenantId(order.getTenantId());
			newOrder.setUserId(order.getUserId());
			Message m = new Message();
			m.setTarget("productTransaction");
			m.addRecipient("productTransactionSvc");
			m.setContent(newOrder);
			try {
				Messenger.send(m);
			} catch (Exception f) {
				f.printStackTrace();
				log.error("消息发送失败..." + newOrder.getOrderId());
			}

			return false;
		}
		return true;
	}

	// @Override
	// @Transactional
	// public boolean cancel(PocOrder order) {
	//
	// boolean flag = false;
	//
	// try {
	// flag = pocOrderBiz.cancelOrder(order.getTenantId(), order);
	// if (!flag) {
	// log.error("撤单失败");
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// log.error("撤单失败...order info :" + order.toString());
	//
	// return false;
	// }
	//
	// return flag;
	// }

	// @Override
	// public PagedResult<PocOrder> findOrder(int tenantId, int orderId, int
	// userId, String orderBy, int pageNo, int pageSize) {
	// return pocOrderBiz.listByOrderIdAndUserId(tenantId, orderId, userId,
	// orderBy, pageNo, pageSize);
	// }
}